import { FolderOutlined, ReadOutlined } from "@ant-design/icons";
import { Button, Checkbox, Form, Input, Layout, Modal, Select, Space, Tree } from "antd";
import { useCallback, useEffect, useReducer } from 'react';
import FillTable from "../../components/FillTable";
import useDrawer from "../../components/useDrawer";
import alert from '../../utils/alert';
import client from '../../utils/client';
import tree from '../../utils/tree';
import styles from '../common.module.css';
import org_styles from './organization.module.css';

export default function Dictionary(props) {
  const [drawer, drawerHolder] = useDrawer({
    placement: "right",
  });
  const [state, dispatch] = useReducer((state, action) => {
    switch (action.type) {
      case 'loaded':
        return {
          ...state,
          selected: null,
          tree_key: Date.now(),
          tree: action.tree,
          defaultExpandedKeys: action.tree.map(d => d.key),
          data: [],
          editing: null,
        };
      case 'update':
        return { ...state, tree: action.tree };
      case 'select':
        return { ...state, selected: action.selected, data: action.data, editing: null };
      case 'reload':
        return { ...state, data: action.data };
      case 'edit':
        return { ...state, editing: action.edit === state.editing ? null : action.edit };
      default:
        return state;
    }
  }, {
    tree_key: Date.now(),
    tree: [],
    defaultExpandedKeys: [],
    // 选中的树节点
    selected: null,
    data: [],
    // 编辑中的记录行
    editing: null,
  });

  const reload_tree = useCallback(() => {
    client.job('TreeR', {
      Card: 'B.枚举类型',
      Model: ['名称', '编码', '叶子节点', '上级'],
      Filter: [['上级', 'is', null]],
      Order: { '名称': 'asc' },
      Parent: '上级',
    }).then(({ Rows }) => {
      dispatch({
        type: 'loaded',
        tree: tree.map(Rows, item => ({
          key: item.ID,
          title: item.名称 + (item.叶子节点 ? ' (' + item.编码 + ')' : ''),
          icon: item.叶子节点 ? <ReadOutlined /> : <FolderOutlined />,
          data: item,
        })),
      });
    });
  }, []);

  // Mount之后自动加载数据
  useEffect(() => {
    reload_tree();
    // eslint-disable-next-line
  }, []);

  const [lx_form] = Form.useForm();
  function edit(record) {
    // 打开抽屉
    record ? lx_form.setFieldsValue(record) : lx_form.resetFields();
    const handle = drawer.open({
      title: record ? '修改节点' : (state.selected ? '新增子节点' : '新增根节点'),
      content: (
        <Form form={lx_form} labelCol={{ span: 6 }}>
          <Form.Item label="名称" name="名称" rules={[{ required: true }]}>
            <Input allowClear={true} autoComplete="off" />
          </Form.Item>
          <Form.Item label="叶子节点" name="叶子节点" initialValue={0}>
            <Select allowClear={true} disabled={record && record.children && record.children.length > 0}>
              <Select.Option value={1}>是</Select.Option>
              <Select.Option value={0}>否</Select.Option>
            </Select>
          </Form.Item>
        </Form>
      ),
      onOk() {
        let ID;
        const promise = record ? Promise.resolve() : client.job('GetGUID').then(ids => ID = ids[0]);
        lx_form.validateFields().then(values => {
          promise.then(() => {
            record = Object.assign({ ID, 上级: state.selected ? state.selected.key : null }, record, values);
            client.job('CardW', {
              Card: 'B.枚举类型',
              Model: ['名称', '编码', '叶子节点', '上级'],
              Record: record,
            }).then(() => {
              handle.destroy();
              reload_tree();
            });
          });
        }).catch(() => null);
      },
    });
  }

  const remove = useCallback(() => {
    if (!state.selected) {
      alert('无效操作', '请先选中您要删除的记录');
      return;
    }

    Modal.confirm({
      title: '删除确认',
      content: "数据删除后不可恢复, 请确定",
      onOk() {
        client.job('TreeD', {
          Card: 'B.枚举类型',
          Parent: '上级',
          Record: state.selected.data,
          Safe: true,
        }).then(() => {
          const data = tree.remove(state.tree, node => node === state.selected);
          dispatch({ type: 'loaded', tree: data });
        });
      }
    });
  }, [state.selected, state.tree]);

  const [sj_form] = Form.useForm();

  useEffect(() => {
    if (state.editing) sj_form.setFieldsValue(state.editing);
    else sj_form.resetFields();
  }, [sj_form, state.editing]);

  const select_sj = useCallback((selected) => {
    if (selected && selected.data.叶子节点) {
      client.job('CardR', {
        Card: 'B.枚举数据',
        Model: ['名称', '序号', '停用', '类型编码', '类型'],
        Filter: [['类型', '=', selected.key]],
        Order: { '序号': 'asc' },
      }).then(({ Rows }) => {
        dispatch({ type: 'select', selected, data: Rows });
      });
    } else {
      dispatch({ type: 'select', selected, data: [] });
    }
    sj_form.resetFields();
  }, [sj_form]);

  const save_sj = useCallback((values) => {
    let ID;
    const promise = state.editing ? Promise.resolve() : client.job('GetGUID').then(ids => ID = ids[0]);
    promise.then(() => {
      const record = Object.assign({ ID, 类型: state.selected.data.ID, 类型编码: state.selected.data.编码 }, state.editing, values);
      client.job('CardW', {
        Card: 'B.枚举数据',
        Model: ['名称', '序号', '停用', '类型编码', '类型'],
        Record: record,
      }).then(() => {
        client.job('CardR', {
          Card: 'B.枚举数据',
          Model: ['名称', '序号', '停用', '类型编码', '类型'],
          Filter: [['类型', '=', record.类型]],
          Order: { '序号': 'asc' },
        }).then(({ Rows }) => {
          dispatch({ type: 'reload', data: Rows });
        });
      });
    });
  }, [state.editing, state.selected]);

  const remove_sj = useCallback((record) => {
    Modal.confirm({
      title: '删除确认',
      content: "数据删除后不可恢复, 请确定",
      onOk() {
        client.job('CardD', {
          Card: 'B.枚举数据',
          Record: record,
          Safe: true,
        }).then(() => {
          // 重新加载数据
          select_sj(state.selected);
        });
      }
    });
  }, [state.selected, select_sj]);

  return (
    <Layout style={{ minWidth: 800 }}>
      <Layout.Sider width={400}>
        <Layout className={styles.container}>
          <Layout.Header className={styles.toolbar}>
            <Space size={[8, 8]} wrap>
              <Button onClick={reload_tree}>刷新</Button>
              <Button type="primary" onClick={() => edit()}
                disabled={state.selected && state.selected.data.叶子节点}>{state.selected ? '新增子节点' : '新增根节点'}</Button>
              <Button onClick={() => edit(state.selected.data)} disabled={!state.selected}>修改</Button>
              <Button onClick={remove} disabled={!state.selected} danger>删除</Button>
            </Space>
          </Layout.Header>
          <Layout.Content>
            <Tree key={state.tree_key} blockNode showIcon rootClassName={org_styles.tree}
              treeData={state.tree} defaultExpandedKeys={state.defaultExpandedKeys}
              selectedKeys={!state.selected ? [] : [state.selected.key]}
              onSelect={(_, { selectedNodes }) => select_sj(selectedNodes[0])}
            />
          </Layout.Content>
        </Layout>
      </Layout.Sider>
      <Layout>
        <Layout.Content>
          <FillTable dataSource={state.data} pagination={false}
            rowSelection={{ hideSelectAll: true, selectedRowKeys: state.editing ? [state.editing.ID] : [] }}
            onRow={record => ({ onClick: () => dispatch({ type: 'edit', edit: record }) })}
            columns={[{
              title: '序号',
              dataIndex: '序号',
              width: 100,
            }, {
              title: '名称',
              dataIndex: '名称',
              ellipsis: true,
            }, {
              title: '停用',
              dataIndex: '停用',
              width: 100,
              render: v => v ? '是' : '否',
            }, {
              title: '操作',
              key: '操作',
              width: 60,
              render(record) {
                return (
                  <Space style={{ color: '#00bfff', cursor: 'pointer' }}>
                    <span onClick={() => remove_sj(record)} style={{ color: 'red' }}>删除</span>
                  </Space>
                );
              },
            }]} />
        </Layout.Content>
        <Layout.Footer className={styles.toolbar} style={{ padding: 20, background: '#fafafa' }}>
          <Form form={sj_form} disabled={!state.selected || !state.selected.data.叶子节点}
            validateMessages={{ required: '' }}
            validateTrigger="onBlur" onFinish={values => save_sj(values)}>
            <Space style={{ alignItems: 'baseline' }}>
              <Form.Item label="序号" name="序号">
                <Input type="number" allowClear={true} />
              </Form.Item>
              <Form.Item label="名称" name="名称" rules={[{ required: true }]}>
                <Input allowClear={true} />
              </Form.Item>
              <Form.Item label="停用" name="停用" valuePropName="checked" initialValue={0}>
                <Checkbox />
              </Form.Item>
              <Button type="primary" htmlType="submit">保存</Button>
            </Space>
          </Form>
        </Layout.Footer>
      </Layout>
      {drawerHolder}
    </Layout>
  )
}